import React from "react";

interface Props extends ITodoItem {
  onDelete: (id: string) => void;
  onUpdate?: (newTodo: ITodoItem) => void;
}

interface State {
  isEdit: boolean;
}

class TodoItem extends React.Component<Props, State> {
  // 初始化 State
  state: Readonly<State> = {
    isEdit: false,
  };

  handleClick = () => {
    console.log("handleClick", this.props.id, this.props.text);

    // 1. 获取当前的Id
    const { id } = this.props;

    // 2. 通知App组件删除
    this.props.onDelete(id);
  };

  handleEdit = () => {
    if (this.state.isEdit) {
      // 保存
      //    1. 要获取到输入框的值【不要使用id或class,而是通过 ref 模板引用】
      // const inputEl = document.querySelector("#input") as HTMLInputElement;
      // const value = inputEl.value;

      const value = (this.refs.input as HTMLInputElement).value;

      this.props.onUpdate?.({
        id: this.props.id,
        text: value,
        isOk: this.props.isOk,
      });
    }

    // 取反
    this.setState((state) => ({ isEdit: !state.isEdit }));
  };

  render(): React.ReactNode {
    const { id, text, isOk } = this.props;
    const { isEdit } = this.state;

    return (
      <div>
        <input type="checkbox" defaultChecked={isOk} />
        <span>{text}</span>
        <button onClick={this.handleClick}>删除</button>

        {/* 受控组件：组件的数据完全有数据（state、props）来控制 */}

        {isEdit && <input ref="input" type="text" defaultValue={text} />}

        <button onClick={this.handleEdit}>{isEdit ? "保存" : "修改"}</button>
      </div>
    );
  }
}

export default TodoItem;
